package com.linkwechat.common.compoment.impl;

import com.linkwechat.common.config.CosConfig;
import com.linkwechat.common.config.IOSSConfig;
import com.linkwechat.common.config.MinoConfig;
import com.linkwechat.common.compoment.IOSSService;
import com.linkwechat.common.utils.file.FileUploadUtils;
import com.linkwechat.common.utils.file.OssMinioUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
@Component
public class OosCompomentImpl implements IOSSService {

    @Autowired
    MinoConfig minoConfig;

    @Autowired
    CosConfig cosConfig;

    @Value("${oss.default}")
    Integer ossdefault;


    @Override
    public String url(String fileNameRelative) {
        String url=null;
        switch (ossdefault){
            case 0:
                url=minoConfig.getEndpoint()+fileNameRelative;
                break;
            case 1:
                url=cosConfig.getImgUrlPrefix()+fileNameRelative;
                break;
            default:
                break;
        }

        return url;

    }

    @Override
    public String upload2oss(MultipartFile file) throws Exception {
        String fileNameRelative=null;
        switch (ossdefault){
            case 0:
                // 设置默认的区块
                String bucket="qlong-qwechat";
                OssMinioUploadUtils.makeBucket(bucket);
                OssMinioUploadUtils.setBucketPolicy(bucket,"read-write");
                fileNameRelative= OssMinioUploadUtils.uploadMultipartFile(bucket,file.getOriginalFilename(),file) ;
                break;
            case 1:
                fileNameRelative= FileUploadUtils.upload2Cos(file,cosConfig);
                break;
            default:
                break;
        }

        return fileNameRelative;
    }

    @Override
    public String upload2oss(InputStream in,String fileEx) throws Exception{
        String fileNameRelative=null;
        switch (ossdefault){
            case 0:
                // 设置默认的区块
                String bucket="qlong-qwechat";
                OssMinioUploadUtils.makeBucket(bucket);
                OssMinioUploadUtils.setBucketPolicy(bucket,"read-write");
                fileNameRelative= OssMinioUploadUtils.uploadInputStream(bucket,fileEx,in) ;
                break;
            case 1:
                String suffix = fileEx.substring(fileEx.lastIndexOf(".") + 1);
                fileNameRelative= FileUploadUtils.upload2Cos(in,suffix,cosConfig);
                break;
            default:
                break;
        }
        return fileNameRelative;
    }
}
